package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.server.mapper.PeachblossomMapper;
import com.tanhua.server.pojo.Peachblossom;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.SoundVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;

/**
 * @Created by ${smh} on 2020/12/9.
 */

@Service
public class PeachblossomService {

    @Autowired
    private PeachblossomMapper peachblossomMapper;

    @Autowired
    protected FdfsWebServer fdfsWebServer;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;



    public void saveSound(MultipartFile soundUrl) {

        User user = UserThreadLocal.get();

        Peachblossom peachblossom = new Peachblossom();
        peachblossom.setUserId(user.getId());

        try {
            //上传视频
            StorePath storePath = storageClient.uploadFile(soundUrl.getInputStream(),
                    soundUrl.getSize(),
                    StringUtils.substringAfter(soundUrl.getOriginalFilename(), "."),
                    null);
            peachblossom.setSoundUrl(fdfsWebServer.getWebServerUrl()  + storePath.getFullPath());
        } catch (Exception e) {
            e.printStackTrace();
        }

        this.peachblossomMapper.insert(peachblossom);
    }

    /**
     * 接收语音
     * @return
     */
    public SoundVo querySound() {

        User user = UserThreadLocal.get();

        QueryWrapper<Peachblossom> wrapper = new QueryWrapper<>();
        //随机一位用户，数据太少，写死了

        /*
        TODO 利用大数据匹配出和该用户匹配的用户，保证这些人不在该用户的喜欢列表里面，
        TODO 按照缘分值从高到低排序，拿到最高得分用户的语音，
        TODO 如果没找到就依次按分数找，如果还是没找到，就随机一个。
        TODO 还要保证用户不能接收重复的语音，每个用户分配一张接受语音记录表，保证不重复
        */

        wrapper.eq("user_id",5);
        Peachblossom peachblossom = this.peachblossomMapper.selectOne(wrapper);
        if(null == peachblossom){
            return null;
        }
        Long userId = peachblossom.getUserId();
        UserInfo userInfo = this.userInfoService.queryUserInfoById(userId);
        if(null == userInfo){
            return null;
        }

        SoundVo soundVo = new SoundVo();
        soundVo.setAge(userInfo.getAge());
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setGender(userInfo.getSex().equals("男") ? "man" : "woman");
        soundVo.setNickname(userInfo.getNickName());
        soundVo.setSoundUrl(peachblossom.getSoundUrl());
        soundVo.setId(Integer.parseInt(userId.toString()));

        //id为当前登录用户的id
        String soundKey = "PEACHBLOSSOM_" + user.getId();
        if(!this.redisTemplate.hasKey(soundKey)){
            //如果不存在key，说明用户今天第一次登录，设置key的值为"1"
            this.redisTemplate.opsForValue().set(soundKey,"1", Duration.ofDays(1));
        }else {
            //获取该用户今天使用的次数
            String s = this.redisTemplate.opsForValue().get(soundKey);
            if(StringUtils.isNotBlank(s)){
                //如果次数大于10了，就把剩余次数设置为0
                if(Integer.parseInt(s) >= 10){
                    soundVo.setRemainingTimes(0);
                }else {
                    //返回剩余次数
                    soundVo.setRemainingTimes(10 - Integer.parseInt(s));
                    //将redis中的value值自增
                    this.redisTemplate.opsForValue().increment(soundKey);
                }
            }
        }
        return soundVo;
    }
}
